# 自定义过滤器 1> 参数接收模板变量 2> 将转换结果返回
import functools

from flask import session, current_app, g

from info.models import User


def func_index_convert(index):

    index_dict = {1:"first", 2:"second", 3:"third"}

    return index_dict.get(index,"")


# 获取用户信息
def user_login_data(f):  # f = news_detail

    @functools.wraps(f)  # 可以让被装饰的函数wrapper使用指定函数的信息(如函数名/函数注释)
    def wrappper(*args, **kwargs):
        # 判断用户是否登录
        user_id = session.get("user_id")
        user = None  # type:User
        if user_id:
            # 查询用户信息
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)

        g.user = user

        return f(*args, **kwargs)

    return wrappper

# 文件上传
def file_upload(data):
    """
    文件上传
    :param data:上传的内容
    :return: 文件名
    """
    import qiniu
    access_key ="8O8gMVzlif_C4Sz_ROaBPnLSrPDGAtiTgwqoLhMi"
    secrect_key ="9A2DNMprkK8FgujjBOtQtGRBNMv5nAlthw53Dcnt"
    bucket_name = "infonews"

    q = qiniu.Auth(access_key,secrect_key)
    key=None # 设置文件名,设置None会生成随机名称
    token =  q.upload_token(bucket_name)
    ret, info = qiniu.put_data(token, key ,data)

    if ret is not None: # 上传成功,返回文件名

            return ret.get("key")   # 获取随机文件名

    else:  #上传成功
        raise BaseException(info)